package com.gonsin.easycount.plugin.impl;

import com.gonsin.easycount.bus.EasyBus;
import com.gonsin.easycount.model.CountGetter;
import com.gonsin.easycount.model.UserInfoOption;
import com.gonsin.easycount.plugin.OuterCache;
import com.gonsin.easycount.plugin.OuterLock;
import com.mchange.v2.util.CollectionUtils;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import static com.google.common.collect.Iterables.isEmpty;

/**
 * 议题触发器
 */
public class TopicNotifier {

    private OuterLock lock;

    private OuterCache cache;

    /**
     * 数据有变化的 topic
     */
    private Set<String> changedTopics;

    private ReadWriteLock myLock = new ReentrantReadWriteLock();

    public TopicNotifier(OuterLock lock, OuterCache cache) {
        this.lock = lock;
        this.cache = cache;
        this.changedTopics = new HashSet<>();
    }

    /**
     * 测试是否可以触发
     */
    public void testNotify() {
        try {
            // 如果该列表为空，则表示数据没有变化
            if(isEmpty(changedTopics)){
                return;
            }
            Set<String> temp = new HashSet<>(changedTopics);
            changedTopics.clear();
            for(String topic : temp){
//                lock.readLock(topic);
//                try {
//
//                } finally {
//                    lock.readUnlock(topic);
//                }
                EasyBus.getInstance().notifyOptionChanged(topic, new CountGetter(topic, lock, cache, false));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
//            myLock.writeLock().unlock();
        }
    }

    public void push(String topic, UserInfoOption userInfoOption) {
//        myLock.writeLock().lock();
//        lock.writeLock(topic);
        try {
            this.changedTopics.add(topic);
        } finally {
//            lock.writeUnlock(topic);
//            myLock.writeLock().unlock();
        }
    }

    /**
     * 立即触发该topic的回调
     */
    public void notify(String topic) {
        EasyBus.getInstance().notifyOptionChanged(topic, new CountGetter(topic, lock, cache, true));
    }
}
